/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 广告控量编辑
 */
import React, { useState, useEffect, useCallback } from 'react';
import { Button, message, Row, Col, Checkbox } from 'antd';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormDateTimeRangePicker,
} from '@ant-design/pro-form';
import moment from 'moment';
import { createControlAdv, copyControlAdv, offlineAdInfo } from '@/services/operatorManagement';
import type { AdvTableControlListItem } from '../types/Advertisements';
import styles from './AdvControlEdit.less';

interface AdvControlEditTypes {
  visible: boolean;
  type: 'add' | 'edit';
  record: AdvTableControlListItem;
  onClose: () => void;
  getList: () => void;
}

const formFields = [
  'plan_id',
  'plan_name',
  'plan_count',
  'is_daily',
  'ad_id',
  'plan_date',
  'remark',
];

const AdvControlEdit: React.FC<AdvControlEditTypes> = ({
  visible,
  type,
  onClose,
  record,
  getList,
}) => {
  const [submiting, setSubmiting] = useState<boolean>(false);
  const [checked, setChecked] = useState<boolean>(false);
  const [adList, setAdList] = useState<string[]>();
  const [form] = ProForm.useForm();

  useEffect(() => {
    if (visible && type === 'edit') {
      setChecked(record.is_daily == '1');
      form?.setFieldsValue({
        plan_id: record.plan_id,
        plan_name: record.plan_name,
        plan_count: record.plan_count,
        is_daily: record.is_daily,
        plan_date: record.plan_date,
        remark: record.remark,
      });
    }
  }, [visible, type, record, form]);

  useEffect(() => {
    offlineAdInfo({ name: record.plan_name }).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        const adListByData = data.map((item: any) => {
          return { label: item.name, value: item.id };
        });
        setAdList(adListByData);
      } else {
        message.error(msg);
      }
    });
  }, [type]);

  const onCancel = useCallback(() => {
    onClose();
    form.resetFields();
  }, [form, onClose]);

  const formatDay = useCallback((time, format = 'YYYY-MM-DD HH:mm:ss') => {
    return moment(time).format(format);
  }, []);

  const onSubmit = useCallback(
    (params) => {
      setSubmiting(true);
      const payload = {
        is_daily: params.checked ? '1' : '2',
        type: type === 'edit' ? 'update' : 'insert',
      };

      const arr = [...formFields];
      form
        .validateFields(arr)
        .then(async (paramsRes) => {
          const {
            plan_date: [plan_date0, plan_date1],
          } = paramsRes;
          const res = {
            ...paramsRes,
            plan_date: JSON.stringify([formatDay(plan_date0), formatDay(plan_date1)]),
          };
          const { code, msg } = await createControlAdv({
            ...res,
            ...payload,
          });
          setSubmiting(false);
          if (code == 0) {
            message.success('提交成功');
            onCancel();
            getList();
          } else {
            message.error(msg);
          }
        })
        .catch(() => {
          setSubmiting(false);
        });
    },
    [type, record, form, getList, onCancel],
  );

  const onCopy = useCallback(async () => {
    const { code, msg } = await copyControlAdv({ plan_id: record.plan_id });
    if (code == 0) {
      message.success('复制成功');
      onCancel();
      getList();
    } else {
      message.error(msg);
    }
  }, [record, getList, onCancel]);

  const changeCheckBox = useCallback(async (values) => {
    setChecked(values.target.checked);
  }, []);

  return (
    <ModalForm
      form={form}
      visible={visible}
      title='控量广告'
      width={800}
      submitter={{
        render: () => [
          <Button
            loading={submiting}
            type='primary'
            key='save'
            onClick={() => onSubmit({ checked })}
          >
            {type === 'add' ? '发布' : '保存'}
          </Button>,
          <span key='copy'>{type === 'edit' && <Button onClick={onCopy}>复制</Button>}</span>,
        ],
      }}
      modalProps={{
        onCancel,
        centered: true,
      }}
      onValuesChange={(changedValues) => {
        console.log(changedValues, '表单change');
      }}
    >
      <ProForm.Group>
        <ProFormText
          width='md'
          name='plan_name'
          label='广告名称'
          placeholder='请输入广告名称'
          rules={[
            {
              required: true,
              message: '请输入广告名称',
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          width='md'
          name='ad_id'
          label='选择广告'
          options={adList}
          rules={[
            {
              required: true,
              message: '请输入广告名称',
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <Row>
          <Col span={8}>
            <ProFormText
              width='md'
              name='plan_count'
              label='广告数量'
              placeholder='请输入'
              rules={[
                {
                  required: true,
                  message: '请输入',
                },
              ]}
            />
          </Col>
          <Col className={styles.checkBox} span={16}>
            <Checkbox
              defaultChecked={checked}
              onChange={changeCheckBox}
              style={{ lineHeight: '32px' }}
            >
              每日控量
            </Checkbox>
          </Col>
        </Row>
      </ProForm.Group>

      <ProForm.Group>
        <ProFormDateTimeRangePicker
          name='plan_date'
          label='日期时间'
          placeholder='请选择'
          rules={[
            {
              required: true,
              message: '请输入广告名称',
            },
          ]}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormText width='md' name='remark' label='备注' placeholder='请输入备注' />
      </ProForm.Group>
    </ModalForm>
  );
};

export default React.memo(AdvControlEdit);
